package com.linpq.activiti.controller;

import com.linpq.activiti.domain.BizTodoItem;
import com.linpq.activiti.service.IProcessService;
import com.linpq.common.core.controller.BaseController;
import com.linpq.common.core.page.TableDataInfo;
import com.linpq.common.utils.ShiroUtils;
import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.StartFormData;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * ClassName : com.linpq.activiti.controller.DynamicFormController
 * Desc : 实现动态表单技术，代码未优化，仅实践了初步可行性。
 *
 * @author : LINPQ
 * @date : 2020/12/22 15:51
 */
@RequestMapping("/dynamic")
@Controller
public class DynamicFormController extends BaseController {

    private String prefix = "dynamic";
    @Autowired
    private FormService formService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IProcessService processService;
    @Autowired
    private TaskService taskService;


    /**
     * 复制流程定义 列表页面中 流程ID 例如：	dynamic:6:12541
     * 浏览器访问 /dynamic/start/dynamic:6:12541 即可打开动态页面
     * @param procDefId
     * @param model
     * @return
     */
    @GetMapping(value = "/start/{procDefId}")
    public String startPage(@PathVariable("procDefId") String procDefId, Model model) {

        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        List<ProcessDefinition> list = processDefinitionQuery.processDefinitionId(procDefId).list();
        ProcessDefinition proc = list.get(0);
        StartFormData startFormData = formService.getStartFormData(procDefId);
        List<FormProperty> formProperties = startFormData.getFormProperties();
        ProcessDefinition pd = startFormData.getProcessDefinition();
        model.addAttribute("list", formProperties);
        model.addAttribute("proc", pd);
        return prefix+"/startpage";
    }

    /**
     * 点击提交审批，可以通过FormProperty 获取 页面中的name 以及对应value 然后转为map，作为流程 过程map
     * 未完成内容：未做页面跳转
     * @param procDefId
     * @param procName
     * @param data
     * @param model
     * @param request
     * @return
     */
    @PostMapping(value = "/start")
    public String startProc(String procDefId, String procName, String data, Model model, HttpServletRequest request){
        StartFormData startFormData = formService.getStartFormData(procDefId);
        List<FormProperty> formProperties = startFormData.getFormProperties();
        ProcessDefinition pd = startFormData.getProcessDefinition();
        boolean hasStartFormKey = pd.hasStartFormKey();
        Map<String, Object> formValues = new HashMap<String, Object>();

        if (hasStartFormKey) { // formkey表单
            Map<String, String[]> parameterMap = request.getParameterMap();
            Set<Map.Entry<String, String[]>> entrySet = parameterMap.entrySet();
            for (Map.Entry<String, String[]> entry : entrySet) {
                String key = entry.getKey();
                formValues.put(key, entry.getValue()[0]);
            }
        } else { // 动态表单
// 先读取表单字段在根据表单字段的ID读取请求参数值
            StartFormData formData = formService.getStartFormData(procDefId);

// 从请求中获取表单字段的值
            formProperties = formData.getFormProperties();
            for (FormProperty formProperty : formProperties) {
                String value = request.getParameter(formProperty.getId());
                formValues.put(formProperty.getId(), value);
            }
        }
        identityService.setAuthenticatedUserId(ShiroUtils.getLoginName());
        ProcessInstance pi = runtimeService.startProcessInstanceById(procDefId, formValues);
        runtimeService.setProcessInstanceName(pi.getId(),procName);
        return "";
    }


    /**
     * 根据个人名字 获取 待办task
     * .processDefinitionKey(key) 可添加作为定向查询
     * @param mmap
     * @return
     */
    @GetMapping()
    public String todoitem(ModelMap mmap) {

        List<Task> tasks = new ArrayList<Task>();
        // 根据当前人的ID查询
        List<Task> todoList = taskService
                .createTaskQuery()
                .taskAssignee("admin")
                .list();
        // 根据当前人未签收的任务
        List<Task> unsignedTasks = taskService
                .createTaskQuery()
                .taskCandidateUser("admin")
                .list();
        // 合并
        tasks.addAll(todoList);
        tasks.addAll(unsignedTasks);
        mmap.put("currentUser", ShiroUtils.getSysUser());
        mmap.put("list", tasks);
        return prefix + "/todoitem";
    }
}
